// pages/mine_detail/minezixun/minezixun.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    appointmentData:[],
    PageNum:1,
    isFetching: false, 
    hasMore: true,
    status: '已完成',
    loading: false,

  },
  

  returnMine(){
    wx.navigateBack({
      delta:1,
    })
  },
  makeEvaluation: function(e){
    const appointmentId = e.currentTarget.dataset.index
    wx.navigateTo({
      url: '../evaluation/evaluation?appointmentId='+appointmentId,
    })

  },

  cancleAppointment: async function(e) {
    const appointmentId = e.currentTarget.dataset.index;

    // 禁用按钮，防止多次点击
    wx.showLoading({
      title: '正在取消...',
    });

    try {
      // 发起网络请求
      await wx.request({
        url: 'http://120.26.112.194:80/api/consultationAppointment/updateStatusByAppointmentId?appointmentId='+ appointmentId +'&status=2',
        method: 'PUT',
      });

      // 请求成功后，更新本地数据
      const updatedData = this.data.appointmentData.map(item => {
        if (item.appointmentId === appointmentId) {
          item.completionStatus = 2; // 更新状态为已取消
        }
        return item;
      });

      // 更新页面数据
      this.setData({
        appointmentData: updatedData
      });

      // 提示用户操作成功
      wx.showToast({
        title: '取消预约成功',
        icon: 'success'
      });
    } catch (error) {
      // 请求失败时，捕获错误并给出提示
      console.error('取消预约失败', error);
      wx.showToast({
        title: '取消预约失败，请重试',
        icon: 'none'
      });
    } finally {
      // 隐藏加载指示器
      wx.hideLoading();
    }
  },

  setStatus: function(e) {
    const status = e.currentTarget.dataset.status;
    this.setData({
      status: status
    });
  },
  formatDate: function (isoString) {
    const date = new Date(isoString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); 
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const user = wx.getStorageSync('user');
  wx.request({
    url: 'http://120.26.112.194:80/api/consultationAppointment/selectByUserId?userId=' + user.userId + '&pageNum=' + this.data.PageNum + '&pageSize=10',
    method: 'GET',
    success: (res) => {
      const formattedData = res.data.data.map(item => ({
        ...item,
        appointmentEndTime: this.formatDate(item.appointmentEndTime),
        appointmentStartTime: this.formatDate(item.appointmentStartTime)
      }));
      

      this.setData({
        appointmentData: formattedData
      });
    },
    fail: (error) => {
      // 请求失败的处理逻辑
      console.error('请求失败', error);
    }
  });
    

  },
  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const user = wx.getStorageSync('user');
    wx.request({
      url: 'http://120.26.112.194:80/api/consultationAppointment/selectByUserId?userId=' + user.userId + '&pageNum=1&pageSize=10',
      method: 'GET',
      success: (res) => {
        const formattedData = res.data.data.map(item => ({
          ...item,
          appointmentEndTime: this.formatDate(item.appointmentEndTime),
          appointmentStartTime: this.formatDate(item.appointmentStartTime)
        }));
        
        this.setData({
          appointmentData: formattedData,
          PageNum:1
        });
      },
      fail: (error) => {
        // 请求失败的处理逻辑
        console.error('请求失败', error);
      }
    });

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.isFetching || !this.data.hasMore) {
      return;
    }
  
    this.setData({
      isFetching: true
    });
  
    const user = wx.getStorageSync('user');
    const pageNum = this.data.PageNum + 1;
  
    wx.request({
      url: 'http://120.26.112.194:80/api/consultationAppointment/selectByUserId?userId=' + user.userId + '&pageNum=' + pageNum + '&pageSize=10', // 替换为实际的服务器地址
      method: 'GET',
      success: (res) => {
        const newData = res.data.data;
        console.log(res.data.data)
        if (newData == null || newData == undefined) {
          this.setData({
            hasMore: false
          });
        } else {
          const formattedData = res.data.data.map(item => ({
            ...item,
            appointmentEndTime: this.formatDate(item.appointmentEndTime),
        appointmentStartTime: this.formatDate(item.appointmentStartTime)
          }));
          this.setData({
            PageNum: pageNum,
            appointmentData: this.data.appointmentData.concat(formattedData),
            isFetching: false
          });
        }
      },
      fail: (res) => {
        console.error('请求失败', res);
        this.setData({
          isFetching: false
        });
        // 提示用户加载失败
        wx.showToast({
          title: '加载失败，请稍后重试',
          icon: 'none'
        });
      }
    });

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})